﻿using System;
using System.Data;
using DevExpress.Web.Data;
using ITViet.Web.App_Code;
using ITViet.Domains;
using ITViet.Services;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxTreeList;
using System.IO;

namespace ITViet.Web.Admin
{
	public partial class ProductList : AdminBasePage
	{
		#region Properties

		private string m_innerError = string.Empty;
		private int m_productid = 0;
		private string ERROR0002 = "error:update|";
		private string ERROR0003 = "error:delete|";
		private string SessionCategoryName = "ProductCategory";
		private string UploadSession = "ProductImage";

		internal override int RequiredPermission
		{
			get
			{
				return (int)FunctionList.Product;
			}
		}

		private int ProductId
		{
			get { return m_productid; }
			set { m_productid = value; }
		}

		private int? SessionCategory
		{
			set
			{
				Session[SessionCategoryName] = value;
			}
			get
			{
				return Session[SessionCategoryName] as int?;
			}
		}

		#endregion

		#region Events
		protected void Page_Load(object sender, EventArgs e)
		{
			imageUpload1.UploadSessionName = UploadSession;
			if (!IsPostBack && !IsCallback)
			{
				LoadCat();
				LoadTreeList();
				LoadList();

				// set category value
				if (SessionCategory.HasValue)
				{
					TreeListNode node = tlCategory.FindNodeByKeyValue(SessionCategory.Value.ToString());
					if (node != null)
					{
						// Tree list
						node.Focus();

						// Combobox
						cbxCategory.Value = SessionCategory;
					}
					else
					{
						SessionCategory = null;
					}
				}
			}

			if (tlCategory.IsCallback)
			{
				LoadTreeList();
			}
		}

		protected void gvList_CustomJSProperties(object sender, ASPxGridViewClientJSPropertiesEventArgs e)
		{
			e.Properties["cpInnerError"] = m_innerError;
		}

		protected void gvList_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
		{
			switch (e.Column.FieldName)
			{
				case "CreatedDate":
					if (gvList.IsNewRowEditing || gvList.IsEditing)
					{
						e.Editor.Value = DateTime.Now;
						e.Editor.Enabled = false;
					}
					break;
				case "CreatedBy":
					if (gvList.IsNewRowEditing || gvList.IsEditing)
					{
						e.Editor.Value = CurrentUser.Username;
						e.Editor.Enabled = false;
					}
					break;
				case "ModifiedDate":
					if (gvList.IsNewRowEditing || gvList.IsEditing)
					{
						e.Editor.Value = DateTime.Now;
						e.Editor.Enabled = false;
					}
					break;
			}
		}

		protected void gvList_HtmlEditFormCreated(object sender, ASPxGridViewEditFormEventArgs e)
		{
			ASPxGridView grid = (ASPxGridView)sender;
			ASPxComboBox combo = (ASPxComboBox)grid.FindEditRowCellTemplateControl((GridViewDataColumn)grid.Columns["Category"], "cbbCategory");
			combo.DataSource = new ProductCategoryService().GetAll();
			combo.DataBind();
			if (ProductId > 0)
			{
				combo.Value = new ProductService().GetById(ProductId).CategoryId;
			}
		}

		protected void gvList_StartRowEditing(object sender, ASPxStartRowEditingEventArgs e)
		{
			ProductId = (int)e.EditingKeyValue;
		}

		protected void gvList_CommandButtonInitialize(object sender, ASPxGridViewCommandButtonEventArgs e)
		{

			if (!CanDelete && e.Button.ButtonType == ColumnCommandButtonType.Delete)
				e.Visible = false;
			if (!CanModify && e.Button.ButtonType == ColumnCommandButtonType.Edit)
			{
				e.Visible = false;
			}
			if (!CanModify && e.Button.ButtonType == ColumnCommandButtonType.New)
			{
				e.Visible = false;
			}
		}

		protected void gvList_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
		{
			string[] para = e.Parameters.Split('|');
			if (para.Length > 0)
			{
				switch (para[0])
				{
					case "changeCategory":
						SessionCategory = Convert.ToInt32(para[1]);
						break;
					default:
						break;
				}

				LoadList();
			}
		}

		protected void gvList_PageIndexChanged(object sender, EventArgs e)
		{
			LoadList();
		}

		protected void ctrlCallback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
		{
			string[] para = e.Parameter.Split('|');
			switch (para[0])
			{
				case "save":
					e.Result = "save|" + SaveProduct();
					break;
				case "delete":
					int id;
					int.TryParse(para[1], out id);
					e.Result = "delete|" + Delete(id);
					break;
			}
		}
		#endregion

		#region Helps
		private void LoadCat()
		{
			DataSet dataSet = new ProductCategoryService().GetByLang(CurrentLanguage.Id);
			cbxCategory.DataSource = dataSet;
			cbxCategory.DataBind();
		}

		private void LoadTreeList()
		{
			DataSet dataSet = new ProductCategoryService().GetByLang(CurrentLanguage.Id);
			tlCategory.DataSource = dataSet;
			tlCategory.DataBind();
		}

		private void LoadList()
		{
			DataSet dataSet = new ProductService().GetModifiedByCategoryId(SessionCategory);
			foreach (DataRow row in dataSet.Tables[0].Rows)
			{
				if (!string.IsNullOrEmpty(row["Image"].ToString()))
				{
					row["Image"] = "../" + row["Image"];
				}
			}

			gvList.DataSource = dataSet;
			gvList.DataBind();
		}

		private string SaveProduct()
		{
			int id;
			int.TryParse(hfPid.Value, out id);
			try
			{
				ProductService productService = new ProductService();
				Product product = productService.GetById(id);
				if (product == null)
				{
					product = new Product();
					product.CreatedDate = DateTime.Now;
					product.CreatedBy = CurrentUser.Username;
				}

				if (Session[UploadSession] != null && Path.GetFileName(Session[UploadSession].ToString()) == Path.GetFileName(imageUpload1.ImagePath))
				{
					string path = Utils.SaveFileFromTemp(Session[UploadSession].ToString(), FolderDirector.UploadImage);
					product.Image = path;
				}

				product.Name = txtName.Text;
				product.CategoryId = int.Parse(cbxCategory.Value.ToString());
				product.Code = VietnameseString.Convert(txtName.Text);
				product.Size = txtSize.Text;
				product.HasInventory = chbInStock.Checked;
				product.ModifiedBy = CurrentUser.Username;
				product.ModifiedDate = DateTime.Now;
				product.Color = "";
				product.HasInventory = chbInStock.Checked;
				product.IsHot = chbIsHot.Checked;
				if (chbColor1.Checked)
				{
					product.Color = ForeColor1.Value;
				}
				if (chbColor2.Checked)
				{
					product.Color += ";" + ForeColor2.Value;
				}
				if (chbColor3.Checked)
				{
					product.Color += ";" + ForeColor3.Value;
				}
				if (chbColor4.Checked)
				{
					product.Color += ";" + ForeColor4.Value;
				}
				if (chbColor5.Checked)
				{
					product.Color += ";" + ForeColor5.Value;
				}
				productService.Save(product);

				Session[UploadSession] = null;
				return Resources.Messages.ERR0005;
			}
			catch (Exception ex)
			{
				WriteLog("", ex);
				return Resources.Messages.ERR0004;
			}
		}

		private string Delete(int id)
		{
			if (id == 0)
			{
				return ERROR0003 + Resources.Messages.ERR0060;
			}
			try
			{
				//TList<ProductLocale> plist = new ProductLocaleService().GetByProductId(id);
				//foreach (ProductLocale item in plist)
				//{
				//  Utils.DeleteFile(MapPath("../" + item.Image));
				//}
				new ProductService().DeleteAllById(id);
				return Resources.Messages.ERR0005;
			}
			catch (Exception ex)
			{
				WriteLog("Product.aspx::Delete Product", ex);
				return ERROR0003 + Resources.Messages.ERR0060;
			}
		}

		private void SetStateGrid(object sender, System.ComponentModel.CancelEventArgs e)
		{
			ASPxGridView gv = sender as ASPxGridView;
			e.Cancel = true;
			gv.CancelEdit();
			LoadList();
		}
		#endregion
	}
}
